package com.jx.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jx.dao.system.RoleDao;
import com.jx.pojo.entity.system.Role;
import com.jx.pojo.vo.system.RoleVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class RoleService extends ServiceImpl<RoleDao, Role> {


    @Resource
    private RoleMenuService roleMenuService;

    /**
     * 获取列表
     */
    public PageInfo<Role> listRole(RoleVO query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(query.getRoleName()), "role_name", query.getRoleName());
        wrapper.like(StringUtils.isNotBlank(query.getRoleKey()), "role_key", query.getRoleKey());
        wrapper.eq(query.getStatus() != null, "status", query.getStatus());
        wrapper.ge(StringUtils.isNotBlank(query.getStartDate()), "create_time", query.getStartDate());
        wrapper.le(StringUtils.isNotBlank(query.getEndDate()), "create_time", query.getEndDate());
        wrapper.orderByAsc("sort");
        List<Role> list = this.list(wrapper);
        return new PageInfo<>(list);
    }

    /**
     * 保存
     */
    @Transactional
    public void saveRole(Role role) {
        Integer id = role.getId();
        LocalDateTime dateTime = LocalDateTime.now();
        if (id == null) {
            role.setCreateTime(dateTime);
        }
        role.setUpdateTime(dateTime);

        this.saveOrUpdate(role);

        // 保存角色菜单关联表
        List<Integer> menuIds = role.getMenuIds();
        roleMenuService.saveRoleMenu(role, menuIds);
    }

    /**
     * 根据id获取明细
     */
    public Role getRoleById(Integer id) {
        Role role = this.getById(id);
        List<Integer> menuIds = roleMenuService.getMenuIdsByRoleId(role.getId());
        role.setMenuIds(menuIds);
        return role;
    }

    /**
     * 修改状态
     */
    public void changeStatus(Integer id, Integer status) {
        Role role = new Role();
        role.setId(id);
        role.setStatus(status);
        this.updateById(role);
    }

    /**
     * 根据id删除
     */
    @Transactional
    public void deleteById(Integer id) {
        this.removeById(id);

        // 删除对应权限
        roleMenuService.deleteByRoleId(id);
    }

    /**
     * 获取角色列表
     */
    public List<Role> getRoleList() {
        return this.list();
    }

}
